<template>
      <el-form-item :label="label">
        <el-upload
          class="avatar-uploader"
          :action="upload_url"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :data="dataObj"
        >
          <img v-if="imageUrl" :src="imageUrl"  class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
</template>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

<script>
  import { getToken} from '@/api/init'

  export default {
    name:'Upload',
    props: {
      label: {
        required: true,
        type: String
      },
      old_path:{
        required: false,
        type: String
      },
      filed:{
        required:false,
        type:String
      }
    },
    data() {
      return {
        upload_url:'',
        upload_token:'',
        dataObj: { token: '' },
        imageUrl: '',
        form:{
          'path':''
        }
      }
    },

    watch:{
        old_path:function(nw,od) {
            this.imageUrl = nw;
        }
    },

    created() {
      this.imageUrl = this.old_path;
      this.getToken();

    },
    methods: {
      getToken(){

          var that = this;
          getToken().then(response => {
              that.upload_url = response.data.url;
              that.upload_token = response.data.token;

              that.dataObj.token = response.data.token;
          }).catch(err => {

          })


        // return new Promise((resolve, reject) => {
        //   getToken().then(response => {
        //     this.upload_url = response.data.url;
        //     this.upload_token = response.data.token;
        //
        //     this.dataObj.token = response.data.token;
        //     resolve(true)
        //   }).catch(err => {
        //     reject(false)
        //   })
        // });
      },

      handleAvatarSuccess(res, file) {
        // this.form.path = res.hash;
        var a = res.replace("hash=","");

         a = a.replace(/"/g,'');

        this.imageUrl = a;
        this.$emit('upload-event',a,this.filed);
      },
    },

  }
</script>

